package com.jinloes.webfit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
public class AccountController {

	@Autowired
    @Qualifier("userService")
	private UserDetailsManager userDetailsService;
	
	@RequestMapping("/account/home")
	public String accountHome() {
        return "accountHome";
	}
	@RequestMapping(value="/account/changePassword",method=RequestMethod.GET)
	public String showChangePasswordPage() {
        return "changePassword";
	}

	@RequestMapping(value="/account/changePassword",method=RequestMethod.POST)
	public String submitChangePasswordPage(@RequestParam("oldpassword") String oldPassword, 
			@RequestParam("password") String newPassword) {

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		String username = principal.toString();

		if (principal instanceof UserDetails) {
		  username = ((UserDetails)principal).getUsername();
		}

        System.out.println("USERNAME IS: " + username);
        userDetailsService.changePassword(username, newPassword);
        SecurityContextHolder.clearContext();

		return "redirect:/";
	}
}